import { defineStore } from 'pinia';

// 微信服务状态管理
export const useWechatStore = defineStore('wechat', {
  state: () => ({
    isRunning: false,
    logs: [],
    errors: [],
    status: null,
    forwardingRules: [],
    selectedGroups: [],
    selectedUsers: [],
    userInfo: null,
    isLoggedIn: false
  }),
  
  actions: {
    // 工具方法：方便记录常规日志
    log(message) {
      const logEntry = {
        time: new Date().toLocaleString(),
        content: typeof message === 'object' ? JSON.stringify(message) : String(message)
      };
      console.log(`[日志] ${logEntry.content}`);
      this.logs.push(logEntry);
      
      // 限制日志数量
      if (this.logs.length > 1000) {
        this.logs.shift();
      }
    },
    
    // 工具方法：方便记录错误日志
    error(message) {
      const errorEntry = {
        time: new Date().toLocaleString(),
        content: typeof message === 'object' ? JSON.stringify(message) : String(message)
      };
      console.error(`[错误] ${errorEntry.content}`);
      this.errors.push(errorEntry);
      
      // 限制错误数量
      if (this.errors.length > 100) {
        this.errors.shift();
      }
    },
    
    // 更新服务状态
    updateStatus(status) {
      this.isRunning = status.running;
      this.status = status;
      
      // 更新登录状态
      if (status.loggedIn !== undefined) {
        this.isLoggedIn = status.loggedIn;
        
        // 记录状态变化到日志
        this.log(`服务状态更新: 运行=${status.running}, 登录=${status.loggedIn}`);
      }
    },
    
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo;
      this.isLoggedIn = true;
      console.log('用户信息已更新:', userInfo);
    },
    
    // 清除用户信息和登录状态
    clearUserInfo() {
      this.userInfo = null;
      this.isLoggedIn = false;
    },
    
    // 添加日志
    addLog(log) {
      this.log(log);
    },
    
    // 添加错误
    addError(error) {
      this.error(error);
    },
    
    // 清空日志
    clearLogs() {
      this.logs = [];
    },
    
    // 清空错误
    clearErrors() {
      this.errors = [];
    },
    
    // 添加转发规则
    addForwardingRule(rule) {
      this.forwardingRules.push(rule);
    },
    
    // 删除转发规则
    removeForwardingRule(index) {
      this.forwardingRules.splice(index, 1);
    },
    
    // 更新转发规则
    updateForwardingRule(index, rule) {
      this.forwardingRules[index] = rule;
    },
    
    // 设置选中的群组
    setSelectedGroups(groups) {
      this.selectedGroups = groups;
    },
    
    // 设置选中的用户
    setSelectedUsers(users) {
      this.selectedUsers = users;
    }
  },
  
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'wechat-store',
        storage: localStorage,
        paths: ['forwardingRules', 'selectedGroups', 'selectedUsers', 'userInfo', 'isLoggedIn']
      }
    ]
  }
}); 